"""
依赖注入模块
============

提供FastAPI依赖注入函数，用于解耦API层和应用层的依赖关系。

设计原则:
- 单一职责: 每个函数只负责提供一个依赖
- 可测试性: 依赖可以轻松被mock替换
- 解耦: API层不直接依赖main.py
- 生命周期管理: 确保资源正确初始化和清理

作者: 架构组
创建日期: 2025-10-05
"""

from typing import Optional
import logging

from .services.core.market_data_service_v2 import MarketDataServiceV2
from .adapters.manager import AdapterManager
from .services.core.cache_service import CacheService
from ..exceptions.market_data_exceptions import ConfigurationException

logger = logging.getLogger(__name__)

# ==================== 全局单例实例 ====================
# 这些实例在应用启动时由main.py初始化

_adapter_manager_instance: Optional[AdapterManager] = None
_market_data_service_instance: Optional[MarketDataServiceV2] = None
_cache_service_instance: Optional[CacheService] = None


# ==================== 设置函数 (由main.py调用) ====================

def set_adapter_manager(manager: AdapterManager) -> None:
    """
    设置全局AdapterManager实例
    
    Args:
        manager: AdapterManager实例
        
    Note:
        此函数应该在应用启动时由main.py调用一次
    """
    global _adapter_manager_instance
    _adapter_manager_instance = manager
    logger.info("AdapterManager dependency registered")


def set_market_data_service(service: MarketDataServiceV2) -> None:
    """
    设置全局MarketDataServiceV2实例
    
    Args:
        service: MarketDataServiceV2实例
        
    Note:
        此函数应该在应用启动时由main.py调用一次
    """
    global _market_data_service_instance
    _market_data_service_instance = service
    logger.info("MarketDataServiceV2 dependency registered")


def set_cache_service(service: CacheService) -> None:
    """
    设置全局CacheService实例
    
    Args:
        service: CacheService实例
    """
    global _cache_service_instance
    _cache_service_instance = service
    logger.info("CacheService dependency registered")


def clear_dependencies() -> None:
    """
    清除所有依赖实例
    
    Note:
        此函数应该在应用关闭时由main.py调用
    """
    global _adapter_manager_instance, _market_data_service_instance, _cache_service_instance
    _adapter_manager_instance = None
    _market_data_service_instance = None
    _cache_service_instance = None
    logger.info("All dependencies cleared")


# ==================== FastAPI依赖注入函数 ====================

async def get_adapter_manager() -> AdapterManager:
    """
    获取AdapterManager实例 (FastAPI依赖注入)
    
    Returns:
        AdapterManager实例
        
    Raises:
        ConfigurationException: 如果AdapterManager未初始化
        
    Example:
        ```python
        @router.get("/adapters/status")
        async def get_adapters_status(
            manager: AdapterManager = Depends(get_adapter_manager)
        ):
            return await manager.health_check()
        ```
    """
    if _adapter_manager_instance is None:
        logger.error("AdapterManager not initialized - check application startup")
        raise ConfigurationException(
            "AdapterManager not initialized. Please ensure the application "
            "has been properly started."
        )
    return _adapter_manager_instance


async def get_market_data_service() -> MarketDataServiceV2:
    """
    获取MarketDataServiceV2实例 (FastAPI依赖注入)
    
    Returns:
        MarketDataServiceV2实例
        
    Raises:
        ConfigurationException: 如果MarketDataServiceV2未初始化
        
    Example:
        ```python
        @router.get("/bars/historical")
        async def get_historical_bars(
            symbol: str,
            service: MarketDataServiceV2 = Depends(get_market_data_service)
        ):
            return await service.get_historical_bars(symbol, ...)
        ```
    """
    if _market_data_service_instance is None:
        logger.error("MarketDataServiceV2 not initialized - check application startup")
        raise ConfigurationException(
            "MarketDataServiceV2 not initialized. Please ensure the application "
            "has been properly started."
        )
    return _market_data_service_instance


async def get_cache_service() -> CacheService:
    """
    获取CacheService实例 (FastAPI依赖注入)
    
    Returns:
        CacheService实例
        
    Raises:
        ConfigurationException: 如果CacheService未初始化
    """
    if _cache_service_instance is None:
        logger.error("CacheService not initialized - check application startup")
        raise ConfigurationException(
            "CacheService not initialized. Please ensure the application "
            "has been properly started."
        )
    return _cache_service_instance


# ==================== 可选依赖 ====================

async def get_adapter_manager_optional() -> Optional[AdapterManager]:
    """
    获取AdapterManager实例 (可选，不抛出异常)
    
    Returns:
        AdapterManager实例或None
        
    Example:
        用于健康检查等不强制要求服务可用的场景
    """
    return _adapter_manager_instance


async def get_market_data_service_optional() -> Optional[MarketDataServiceV2]:
    """
    获取MarketDataServiceV2实例 (可选，不抛出异常)
    
    Returns:
        MarketDataServiceV2实例或None
        
    Example:
        用于健康检查等不强制要求服务可用的场景
    """
    return _market_data_service_instance


async def get_cache_service_optional() -> Optional[CacheService]:
    """
    获取CacheService实例 (可选，不抛出异常)
    
    Returns:
        CacheService实例或None
    """
    return _cache_service_instance


# ==================== 依赖状态检查 ====================

def is_dependencies_initialized() -> bool:
    """
    检查所有依赖是否已初始化
    
    Returns:
        bool: True表示所有依赖已初始化
    """
    return (
        _adapter_manager_instance is not None and
        _market_data_service_instance is not None and
        _cache_service_instance is not None
    )


def get_dependencies_status() -> dict:
    """
    获取依赖初始化状态
    
    Returns:
        dict: 包含各个依赖的初始化状态
    """
    return {
        "adapter_manager": _adapter_manager_instance is not None,
        "market_data_service": _market_data_service_instance is not None,
        "cache_service": _cache_service_instance is not None,
        "all_initialized": is_dependencies_initialized(),
    }
